package jvlite.aop;

import java.lang.reflect.Method;

import jvlite.ioc.BeanFactory;
import jvlite.mvc.annotaion.PointCut;
import jvlite.util.StrUtil;

public class ProxyExecutor {
	public static Object exec(String clzName, Method method, Object[] args)
			throws Throwable {
		Object rtVal = null;
		Object proxyObj = BeanFactory.getDIMap().get(clzName);
		ProxyHandler proxyHandler = new ProxyHandler();
		IAdvice advice = getAdvice(clzName);
		rtVal = proxyHandler.execute(proxyObj, advice, method, args);
		return rtVal;
	}

	public static IAdvice getAdvice(String clzName) {
		// deal with point cut
		Class<?> clz = null;
		try {
			clz = Class.forName(clzName);
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		PointCut pointCut = clz.getAnnotation(PointCut.class);
		String adviceName = pointCut.advice();

		IAdvice advice = null;
		if (null == adviceName || "".equals(adviceName)) {
			advice = new DefaultAdvice();// default advice
		} else {
			for (Object object : BeanFactory.getDIMap().values()) {// search_for_advice
				Class<?> clazz = object.getClass();
				String cName = clazz.getName();
				String sName = cName.substring(cName.lastIndexOf(".") + 1);// name_without_path
				if (sName.equals(StrUtil.firstUp(adviceName))) {
					try {
						advice = (IAdvice) Class.forName(cName).newInstance();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		}
		return advice;
	}
}